package com.awesome.activitydemo.utils;

import android.app.Activity;

import java.util.Stack;

/**
 * Author: zhangjingfang
 * Email:zhangjingfang@jeejio.com
 * Date: 2022/3/10
 * Description:类描述
 */
public class ActivityManager {
  private final static Stack<Activity> mActivityStack = new Stack<>();

  public static boolean addActivity(Activity activity){
    return mActivityStack.add(activity);
  }

  public static boolean removeActivity(Activity activity){
    return mActivityStack.remove(activity);
  }

  /**
   * Author: zhangjingfang
   * Email: zhangjingfang@jeejio.com
   * Date: 2022/3/10
   * Description: 返回栈顶Activity
   */
  public static Activity getTopActivity() {
    if (mActivityStack.empty()) return null;
    return mActivityStack.peek();
  }

  /**
   * Author: zhangjingfang
   * Email: zhangjingfang@jeejio.com
   * Date: 2022/3/10
   * Description: 返回栈中指定Activity最靠近栈顶的那一个
   */
  public static Activity getTopActivity(Class<?> clazz){
    for (int i = mActivityStack.size() - 1; i > 0; i--) {
      if (clazz == mActivityStack.elementAt(i).getClass()) {
        return mActivityStack.elementAt(i);
      }
    }
    return null;
  }

  /**
   * Author: zhangjingfang
   * Email: zhangjingfang@jeejio.com
   * Date: 2022/3/10
   * Description: 返回所有的Activity
   */
  public static  Stack<Activity>  getActivity(){
    if (mActivityStack.empty()) return null;
    return mActivityStack;
  }

  /**
   * Author: zhangjingfang
   * Email: zhangjingfang@jeejio.com
   * Date: 2022/3/10
   * Description: 清退栈中所有Activity
   */
  public static void exitActivity() {
    while (true) {
      Activity topActivity = getTopActivity();
      if (topActivity == null) break;
      if (removeActivity(topActivity)) {
        topActivity.finish();
      }
    }
  }
  /**
   * Author: zhangjingfang
   * Email: zhangjingfang@jeejio.com
   * Date: 2022/3/10
   * Description: 清退栈中指定Activity上所有的Activity
   */
  public static void exitActivity(Class<?> clazz) {
    while (true) {
      Activity topActivity = getTopActivity();
      if (topActivity == null || clazz == topActivity.getClass()) {
        break;
      }
      if (removeActivity(topActivity)) {
        topActivity.finish();
      }
    }
  }
} 
 
 